package jsu.blogger.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import io.jsonwebtoken.Claims;
import jsu.blogger.service.impl.LoginAndRegisterServiceImpl;
import jsu.blogger.util.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/*
过滤token是否合法
*/
@Component
@Order(1)
@WebFilter("/")
public class TokenFilter extends BaseFilter {
    private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);
    @Autowired
    private LoginAndRegisterServiceImpl loginAndRegister;
    @Override
    protected void doHttpFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 登录注册请求直接放行
        if (isLoginOrRegisterRequest(request)) {
            chain.doFilter(request, response);
            return;
        }

        // 将 ServletRequest 转换为 HttpServletRequest
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        // 将 ServletResponse 转换为 HttpServletResponse
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取请求头部信息
        String tokenHeader = httpRequest.getHeader("token");
        String uidHeader = httpRequest.getHeader("uid");

        // 验证 token 和 uid 是否匹配
        if (tokenHeader != null && uidHeader != null) {
            try {
                // 解析 token
                Claims claims = TokenUtil.parseJWT(tokenHeader);

                // 可选：进一步验证 uid 是否与 token 中的用户信息匹配
                String uidFromToken = claims.get("uid", String.class);
                String passwordFromToken = claims.get("password", String.class);
                Long uid=Long.parseLong(uidFromToken);
                boolean b=loginAndRegister.VerifyUIdAndPassword(uid, passwordFromToken);
                if (uidFromToken != null && uidFromToken.equals(uidHeader)&&b) {
                    // 继续处理请求
                    chain.doFilter(request, response);
                    return;
                } else {
                    log.info("UID和密码不匹配 或 UID和token不匹配");
                    httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
                }
            } catch (Exception e) {
                log.info("Token 验证失败: " + e.getMessage());
                httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            }
        } else {
            log.info("token或uid为空");
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        }
    }

    private boolean isLoginOrRegisterRequest(ServletRequest request) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestURI = httpRequest.getRequestURI();

        // 使用包含关系检查 URI
        return requestURI.contains("/login")
                || requestURI.contains("/register")
                || requestURI.contains("/post/getRecommendedBlogs")||requestURI.contains("/file/")
                || requestURI.contains("/post/getBlogData")| requestURI.contains("/live/getLive")
                || requestURI.contains("/live/getRecommendLive")
                || requestURI.contains("/getComments");
    }
}
